﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SharpSNS.Auth
{
    /// <summary>
    /// Encapsulates the data returned by the server after a clientLogin API call
    /// </summary>
    public class ClientLoginResponse : ApiResponse
    {
        private string _AuthToken;
        /// <summary>
        /// Gets the authorization token -- only set if the status code is 200 (Successful)
        /// </summary>
        public string AuthToken
        {
            get { return _AuthToken; }
        }

        private string _SessionKey;
        /// <summary>
        /// Gets the session key, a hashed value calculated from the user's password and a returned session secret
        /// </summary>
        public string SessionKey
        {
            get { return _SessionKey; }
        }

        private long _HostTime;
        /// <summary>
        /// Gets the Epoch time on the host server at the time of the response -- only set if the status code is 200 (Successful)
        /// </summary>
        public long HostTime
        {
            get { return _HostTime; }
        }

        private long _TimeDifference;
        /// <summary>
        /// Gets the difference in time between the host's clock and the client computer -- only set if the status code is 200 (Successful)
        /// </summary>
        public long TimeDifference
        {
            get { return _TimeDifference; }
        }

        /// <summary>
        /// Initializes the ClientLoginResponse with the specified response element
        /// </summary>
        /// <param name="responseNode">Response XML node received from server</param>
        /// <param name="password">Password of the user</param>
        public ClientLoginResponse(XmlNode responseNode, string password)
            : base(responseNode)
        {
            if (ResponseCode == ApiResponseCode.Success)
            {
                XmlNode dataNode = responseNode["data"];
                string sessionSecret = dataNode["sessionSecret"].InnerText;
                long hostTime = long.Parse(dataNode["hostTime"].InnerText);
                _AuthToken = dataNode["token"]["a"].InnerText;
                _SessionKey = RequestSigning.HMACSHA256Base64(password, sessionSecret);
                _HostTime = hostTime;
                _TimeDifference = hostTime - Epoch.GetDifference(DateTime.Now);
            }
        }
    }
}
